package com.example.msgBoard.mapper;

import com.example.msgBoard.model.Message;
import org.apache.ibatis.annotations.*;
import java.util.List;

@Mapper
public interface MessageMapper {
    @Insert("INSERT INTO messages(user_id, username, parent_id, content) VALUES(#{userId}, #{username}, #{parentId}, #{content})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertMessage(Message message);

    @Select("SELECT m.*, u.username FROM messages m JOIN users u ON m.user_id = u.id WHERE m.id = #{id}")
    @Results({
        @Result(property = "username", column = "username")
    })
    Message getMessageById(int id);
@Select("SELECT m.id, m.content, m.created_at, m.user_id, u.username ,m.updated_at FROM messages m JOIN users u ON m.user_id = u.id WHERE m.parent_id IS NULL ORDER BY m.created_at DESC")
@Results({
    @Result(property = "id", column = "id"),
    @Result(property = "content", column = "content"),
    @Result(property = "createdAt", column = "created_at"),
    @Result(property = "updatedAt", column = "updated_at"),
    @Result(property = "userId", column = "user_id"),
    @Result(property = "username", column = "username"),
    @Result(property = "replies", column = "id", javaType = List.class,
            many = @Many(select = "getRepliesByParentId"))
})
List<Message> getAllRootMessages();


    @Select("SELECT m.*, u.username FROM messages m JOIN users u ON m.user_id = u.id WHERE m.parent_id = #{parentId} ORDER BY m.created_at ASC")
    @Results({
        @Result(property = "username", column = "username")
    })
    List<Message> getRepliesByParentId(int parentId);

    @Update("UPDATE messages SET content = #{content} WHERE id = #{id}")
    void updateMessage(Message message);

    @Delete("DELETE FROM messages WHERE id = #{id}")
    void deleteMessage(int id);
}
